import time
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response
from core.logger.proxy import logger
from core.context.ctxmgr import context_manager


class AccessLogMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next) -> Response:
        try:
            ctx = context_manager.get_context()
            ctx.set("request_id", request.query_params.get("request_id", "unknown"))
            st = time.perf_counter()
            response = await call_next(request)
            duration_ms = (time.perf_counter() - st) * 1000
            logger.info(
                "HTTP Request",
                {
                    "method": request.method,
                    "path": request.url.path,
                    "query_params": dict(request.query_params),
                    "status_code": response.status_code,
                    "duration_ms": round(duration_ms, 2),
                },
            )
            return response
        finally:
            # 确保上下文释放
            context_manager.release_context()
